package org.nutboat.app;

import org.nutboat.core.GameSystem;
import org.nutboat.core.exception.RunnerInterruptedException;

public final class GameRunner {
	private int fps;
	private long duration;
	private boolean running;
	private Thread runnerThread;
	private GameSystem system;
	
	GameRunner(GameSystem system) {
		fps = 30;
		running = false;
		runnerThread = null;
	}

	public int getFPS() {
		return fps;
	}
	
	public void setFPS(int fps) {
		if (this.fps != fps) {			
			this.fps = fps;
			duration = 1000 /fps;
		}
	}
	
	public boolean isRunning() {
		return running;
	}
			
	void on() {
		if (runnerThread != null && runnerThread.isAlive()) {
			return;
		}
		runnerThread = new Thread() {

			@Override
			public void run() {
				duration = 1000 / fps;
				running = true;
				while (running) {
					system.update();
					try {
						Thread.sleep(duration);
					} catch (InterruptedException e) {
						throw new RunnerInterruptedException(e);
					}
				}
			}
		};
		runnerThread.setDaemon(true);
		
		system.startup();
		runnerThread.start();
	}
	
	void off() {
		running = false;
		system.shutdown();
	}
}